package baiqitun.stupro.api.controller;

import baiqitun.stupro.common.exception.enums.support.StuproExceptionEnum;
import baiqitun.stupro.common.exception.StuproException;
import baiqitun.stupro.common.model.Result;
import baiqitun.stupro.common.service.CaptchaService;
import baiqitun.stupro.common.util.ResultUtil;
import cn.hutool.captcha.ICaptcha;
import cn.hutool.http.ContentType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.Charset;

/**
 * 验证码控制器
 * @author kedaji
 */
@RequestMapping("/captcha")
@Api(description = "图片验证码控制器")
@Slf4j
@Controller
public class CaptchaController {
    @Autowired
    private CaptchaService captchaService;

    @ApiOperation("生成图片验证码")
    @ResponseStatus(HttpStatus.OK)
    @GetMapping(value = "/generate",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public void generate(@ApiParam("图片宽度") Integer width, @ApiParam("图片高度") Integer height,
                         HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (width == null || width <= 0){
            width = 600;
        }
        if (height == null || height <= 0){
            height = 200;
        }
        ICaptcha captcha = captchaService.save(request, width, height);
        response.setContentType(ContentType.build(MediaType.IMAGE_JPEG_VALUE, Charset.forName("UTF-8")));
        try
                (
                        ServletOutputStream outputStream = response.getOutputStream();
                )
        {
            captcha.write(outputStream);
        }
    }


    @ResponseBody
    @ApiOperation("验证码校验")
    @ResponseStatus(HttpStatus.OK)
    @PostMapping(value = "/verify", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Result<?> verify(HttpServletRequest request, @ApiParam("验证码") String captcha){
        boolean passed = captchaService.verify(request, captcha);
        if (! passed){
            throw new StuproException(StuproExceptionEnum.CAPTCHA_ERROR);
        }
        return ResultUtil.ok();
    }
}
